package com.hk.yajin.base;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.developmentlib.base.AppManagerUtils;
import com.hk.developmentlib.utills.NetworkInfoUtils;
import com.hk.developmentlib.utills.UiUtil;
import com.hk.yajin.R;
import com.hk.yajin.function.MainActivity;
import com.hk.yajin.function.members.activity.RegisterUserNameActivity;
import com.umeng.message.PushAgent;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static anet.channel.util.Utils.context;


/**
 * activity基类
 *
 * @author lwb
 */

public class BaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener {
    /*
    * 1.读、写权限
    * 2.相机
    * 3.联系人读写，获取账号GET_ACCOUNTS
    * 4.获取定位
    *5.监听电话状态，打电话
    *6.录音
    *7.短信组
    * */
    protected String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_SMS,
    };
    private RelativeLayout mContainer;
    protected Toolbar toolbar;

    private static final String TAG = "BaseActivity";

    protected Resources res;

    protected Context mContext;

    public static final String ID = "id";
    public static final String URL = "url";
    public static final String VIDEO = "video";
    public static final String DATA_STRING = "data";
    public static final String PUSH_DATA = "pushdata";
    protected String dataString;
    protected Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushAgent.getInstance(context).onAppStart();
        this.res = this.getResources();
        this.mContext = this;
        AppManagerUtils.getAppManager().addActivity(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressd();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    protected void onBackPressd() {
        finish();
    }

    protected void initToolBar(int titleId) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setBackgroundColor(UiUtil.getColor(R.color.white));
        toolbar.setTitle("");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressd();
            }
        });
        TextView textView = (TextView) findViewById(R.id.tv_title);
        textView.setText(UiUtil.getString(titleId));
        textView.setTextColor(UiUtil.getColor(R.color.black_282828));
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManagerUtils.getAppManager().finishActivity(this);

    }

    protected void showShortToast(int pResId) {
        showShortToast(getString(pResId));
    }

    protected void showLongToast(String pMsg) {
        Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show();
    }

    protected void showShortToast(String pMsg) {
        Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show();
    }

    protected boolean hasExtra(String pExtraKey) {
        if (getIntent() != null) {
            return getIntent().hasExtra(pExtraKey);
        }
        return false;
    }

    protected void openActivityForResult(Class<?> pClass, int requestCode) {
        openActivityForResult(pClass, requestCode, null);
    }

    protected void openActivityForResult(Class<?> pClass, int requestCode, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivityForResult(intent, requestCode);

    }

    protected void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        imm.showSoftInput(view, 0);
    }


    /**
     * 判断键盘是否显示
     *
     * @return
     */
    protected boolean isShowKeyboard() {
        return getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {

    }

    @Override
    public void onClick(View v) {

    }


    protected boolean isNetWorkConnect() {
        if (new NetworkInfoUtils(this).getNetType() == -1) {
            showShortToast(getString(R.string.badnetwork));
            return false;
        } else {
            return true;
        }
    }

    protected void startActivity(Class<?> cls) {
        startActivity(new Intent(this, cls));
    }


    protected void showAlertDialog(String title, String Content, DialogInterface.OnClickListener postClicklister) {
        new AlertDialog.Builder(this).setTitle(title)//设置对话框标题
                .setMessage(Content)
                .setPositiveButton("确定", postClicklister)
                .setNegativeButton("取消", null)
                .show();
    }

    public static void starItSelf(Context context, Class<?> cla) {
        context.startActivity(new Intent(context, cla));
    }

    /*********************LoadingView相关方法***********************/

    private View loadingView;

    public void showLoadingViewWhiteBg() {
        initLoadingView();
        loadingView.setBackgroundColor(Color.WHITE);
        if (loadingView.getVisibility() != View.VISIBLE) {
            loadingView.setVisibility(View.VISIBLE);
        }
    }

    public void showLoadingView() {
        initLoadingView();
        if (loadingView.getVisibility() != View.VISIBLE) {
            loadingView.setBackgroundColor(Color.TRANSPARENT);
            loadingView.setVisibility(View.VISIBLE);
            hideKeyboard(loadingView);
        }

    }


    public void hideLoadingView() {
        if (loadingView != null && loadingView.getVisibility() != View.GONE) {
            loadingView.setVisibility(View.GONE);
        }
    }

    private void initLoadingView() {
        if (loadingView == null) {
            loadingView = View.inflate(this, R.layout.loading_view, null);
            loadingView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
            mContainer.addView(loadingView, getLayoutParams());
        }
    }

    private RelativeLayout.LayoutParams getLayoutParams() {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        return lp;
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        setContentView(View.inflate(this, layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(initContentView(view));
    }

    protected View initContentView(View view) {
        mContainer = new RelativeLayout(this);
        mContainer.addView(view, getLayoutParams());
        return mContainer;
    }

    /*确认框*/
    public void showConfrimDialog(String content, DialogInterface.OnClickListener clickListener) {
        new AlertDialog.Builder(this).setTitle("提示")//设置对话框标题
                .setMessage(content)
                .setPositiveButton("确定", clickListener)
                .setNegativeButton("取消", null)
                .show();
    }

    /*确认框*/
    public void showConfrimDialog() {
        new AlertDialog.Builder(this).setTitle("提示")//设置对话框标题
                .setMessage("昵称设置尚未完成，确定现在退出吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.starItSelf(getApplicationContext(), MainActivity.class);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}
